/*
 * Copyright (c) 2019 Hitevision
 */

package tw.com.hitevision.whiteboard.android.util;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

public class ContentProviderUtils {

    public static int update(Context context, Uri contentUri, String key, int value) {
        final ContentResolver resolver = context.getContentResolver();
        final ContentValues values = new ContentValues();

        values.put(key, value);

        try {
            return resolver.update(contentUri, values, null, null);
        } catch (NullPointerException exception) {
            return 0;
        }
    }

    public static int update(Context context, Uri contentUri, String key, String value) {
        final ContentResolver resolver = context.getContentResolver();
        final ContentValues values = new ContentValues();

        values.put(key, value);

        try {
            return resolver.update(contentUri, values, null, null);
        } catch (NullPointerException exception) {
            return 0;
        }
    }

    public static int queryInteger(Context context, Uri contentUri, String key) {
        final ContentResolver resolver = context.getContentResolver();
        final Cursor cursor = resolver.query(contentUri, new String[] {key}, null, null, null);

        int value = 0;
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                value = cursor.getInt(cursor.getColumnIndex(key));
            }
            cursor.close();
        }

        return value;
    }

    public static String queryString(Context context, Uri contentUri, String key) {
        final ContentResolver resolver = context.getContentResolver();
        final Cursor cursor = resolver.query(contentUri, new String[] {key}, null, null, null);

        String value = null;
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                value = cursor.getString(cursor.getColumnIndex(key));
            }
            cursor.close();
        }

        return value;
    }
}
